package org.grow.present.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @Author: xwg
 * @CreateDate: 2024/6/5
 */

@Service
public class FileTransfer {
    @Value("${present.common.image-location}")
    private String location;

    public String transTo(String pic,String UID,String tableName) throws IOException {
//        System.out.println(pic);
//        String pic = userInfo.getPic();
//        Path source = Path.of(location).resolve("temp").resolve(pic);
//        pic likes "" | /temp/PIC000001.png
        if(!StringUtils.hasText(pic)) return "";
        Path source = Paths.get(location+pic);
//        Path source = Path.of(location).resolve(pic);
//        Path source = Path.of(location).resolveSibling()
//        sourde likes   /home/xxx/temp/PIC000001.png
//        System.out.println(source);
        String ext = pic.substring(pic.lastIndexOf("."));
//        ext likes .png
        String newPic = UID + ext;
//        newPic likes BB0000000101.png
//        Path p = Path.of(location).resolve("UserInfo");
        Path p = Path.of(location).resolve(tableName);
//        p likes /home/xxx/BBill
        if (Files.notExists(p)) {
                Files.createDirectories(p);
        }
//
        Path target = p.resolve(newPic);
//        target likes /home/xxx/BBill/BB0000000101.png
        System.out.println(" try transfer to "+ source +" => "+target);
        Files.move(source,target, StandardCopyOption.REPLACE_EXISTING);
//        likes  /BBill/BB0000000101.png
        return "/"+tableName+"/"+newPic;
    }
}
